<?php
/*
 * (C) Copyright 2013 Torsten Gorath (http://www.blauesdach.de/).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Contributors:
 *     Torsten Gorath
 */
require_once $basedir.'/inc/permissions.php';
require_once $basedir.'/inc/role.php';

$id = isset($_REQUEST['id'])?$_REQUEST['id']:"";
$name = isset($_REQUEST['name_require'])?$_REQUEST['name_require']:"";
$description = isset($_REQUEST['description'])?$_REQUEST['description']:"";
$permission_id = isset($_REQUEST['new_permission'])?$_REQUEST['new_permission']:"";

$error = false;
/*
 * Save data
 */
if((isset($_REQUEST['save_permission']) || isset($_REQUEST['save']))) {
    if((isset($_REQUEST['save_permission']) || isset($_REQUEST['save'])) && $id == "") {
        if($name == "") {
            $error = true;
            $msg = "Rolename is missing";
        } else {
            $id = Role::insertRole($name);
            $msg = "Save role";
        }
    }
    $role = null;
    if($id != "" && !$error) {
        $role = new Role($id);
        $role->setDescription($description);
        $error = !$role->save();
        if($error) {
            $msg = "Can't save role";
        }
    }
    if($role != null && !$error) {
        $error = !$role->addPerm($permission_id);
        if($error) {
            $msg = "Can't add permission";
        }
    }
/*
 * read data
 */
} else if(isset($_REQUEST['get'])) {
    $role = null;
    if($id != "") {
        $role = new Role($id);
    } else if($name != "") {
        $role = new Role(null, $name);
    }
    die(json_encode($role->getJsonData()));
}
die("{\"error\":".$error.", \"msg\":\"".$msg."\"}");
?>
